package com.ruoyi.common.security.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/***
 *  @describe 中国联通短信平台接口
 *  @author SUNLIANG
 *  @date 2023/10/30
 *  杰能科世智能安全科技（杭州）有限公司
 *  云通信平台帐号已开通。
 *  网址：http://ytx.i5gmsg.com:9098/
 *  企业名称：杰能科世智能安全科技(杭州)有限公司
 *  登录账号：13175012283
 *  企业编码：11373
 *  登录密码：YTX2021
 */

@Slf4j
@Component
public class ChinaUnicomSmsUtil {

    /**
     * @describe 短信地址
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private static final String SMS_URL = "http://ytx.i5gmsg.com:9098/api/send?SpCode=[SPCODE]" +
            "&LoginName=[LOGINNAME]&Password=[PASSWORD]&MessageType=2&MessageContent=[MESSAGECONTENT]" +
            "&UserNumber=[USERNUMBER]&SerialNumber=[SERIALNUMBER]&ScheduleTime=[SCHEDULETIME]&f=1&AutographId=[AUTOGRAPHID]";
    /**
     * @describe 企业编码
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private static final String SP_CODE = "11373";
    /**
     * @describe 用户名
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private static final String LOGIN_NAME = "13175012283";
    /**
     * @describe 密码
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private static final String PASSWORD = "YTX2021";

    /**
     * @describe 签名为杰能科世
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public static final String AUTOGRAPHID_JNKS = "11916";

    /**
     * @describe 签名为在浙飞
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public static final String AUTOGRAPHID_ZZF = "12798";

    public static void main(String[] args) {
        int random = new Random().nextInt(900000) + 100000;
        log.info("六位短信验证码:" + random);

        new ChinaUnicomSmsUtil().sendMessageByAutographId("15524738073", "您正在登录《麒云低空管理服务系统》，验证码：" + random + "（有效期5分钟）", ChinaUnicomSmsUtil.AUTOGRAPHID_ZZF);
//        new ChinaUnicomSmsUtil().sendMessage("15524738073", "您正在登录《麒云低空管理服务系统》，验证码：" + random + "（有效期5分钟）");
    }

    /**
     * @describe 发送短信
     * @method sendMessage
     * @params [message, type]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public boolean sendMessage(String phone, String message) {
        try {
            String get = sendRequest(initUrl(phone, message), "GET");
            log.info("chinaunion sms commit result: {}", new String(get.getBytes("GBK")));
            if ("result=0&description=提交短信成功".equals(new String(get.getBytes("GBK")))) {
                log.info("验证码发送成功！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("GET短信发送发生异常", e);
            return false;
        }
        return true;
    }

    /**
     * @describe 发送短信
     * @method sendMessage
     * @params [message, type]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public boolean sendMessageByAutographId(String phone, String message, String autographId) {
        try {
            String get = sendRequest(initUrl(phone, message, autographId), "GET");
            log.info("chinaunion sms commit result: {}", new String(get.getBytes("GBK")));
            if ("result=0&description=提交短信成功".equals(new String(get.getBytes("GBK")))) {
                log.info("短信发送成功！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送发生异常", e);
            return false;
        }
        return true;
    }

    /**
     * @describe 初始化短信地址
     * @method initUrl
     * @params [phone, message]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private String initUrl(String phone, String message) throws Exception {
        Date date = Calendar.getInstance().getTime();
        String scheduleTime = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        String serialNumber = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date) + this.getThreeRandomNumbers();
        String url = SMS_URL.replace("[SPCODE]", SP_CODE).replace("[LOGINNAME]", LOGIN_NAME)
                .replace("[PASSWORD]", PASSWORD).replace("[MESSAGECONTENT]", encodeStr(message))
                .replace("[USERNUMBER]", phone).replace("[SERIALNUMBER]", serialNumber)
                .replace("[SCHEDULETIME]", scheduleTime).replace("[AUTOGRAPHID]", AUTOGRAPHID_JNKS);

        log.info("请求url地址={}", url);
        return url;
    }

    /**
     * @describe 初始化短信地址
     * @method initUrl
     * @params [phone, message]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private String initUrl(String phone, String message, String AutographId) throws Exception {
        Date date = Calendar.getInstance().getTime();
        String scheduleTime = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        String serialNumber = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date) + this.getThreeRandomNumbers();
        String url = SMS_URL.replace("[SPCODE]", SP_CODE).replace("[LOGINNAME]", LOGIN_NAME)
                .replace("[PASSWORD]", PASSWORD).replace("[MESSAGECONTENT]", encodeStr(message))
                .replace("[USERNUMBER]", phone).replace("[SERIALNUMBER]", serialNumber)
                .replace("[SCHEDULETIME]", scheduleTime).replace("[AUTOGRAPHID]", AutographId);

        log.info("请求url地址={}", url);
        return url;
    }

    /**
     * @describe 加密
     * @method encodeStr
     * @params [str]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public String encodeStr(String str) throws UnsupportedEncodingException {
        return URLEncoder.encode(str, "gbk");
    }

    /**
     * @describe 发送消息
     * @method sendRequest
     * @params [urlParam, requestType]
     * @author SUNLIANG
     * @date 2023/10/30
     */
    public static String sendRequest(String urlParam, String requestType) throws IOException {
        HttpURLConnection con = null;
        BufferedReader buffer = null;
        StringBuffer resultBuffer = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlParam);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(requestType);
            con.setRequestProperty("Content-Type", "application/json;charset=GBK");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = con.getInputStream();
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (buffer != null) {
                buffer.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return "";
    }

    /**
     * @describe 三位随机数
     * @method getThreeRandomNumbers
     * @params []
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private int getThreeRandomNumbers() {
        return new java.util.Random().nextInt(900) + 100;
    }

    /**
     * @describe 六位随机数
     * @method getThreeRandomNumbers
     * @params []
     * @author SUNLIANG
     * @date 2023/10/30
     */
    private int getSixRandomNumbers() {
        return new java.util.Random().nextInt(900000) + 100000;
    }

}
